package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginCheckFilter")
public class LoginCheckFilter implements Filter {
    private String[] URL = new String[]{"/backend/**", "/front/**", "/employee/login", "/employee/logout", "/common/**","/user/sendMsg","/user/login"};

    public boolean isCheck(String requestURI) {
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String s : URL) {
            if (antPathMatcher.match(s, requestURI)) {
                return true;
            }
        }
        return false;
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String requestURI = request.getRequestURI();

        if (isCheck(requestURI)) {
            chain.doFilter(request, response);
            return;
        }
        if (request.getSession().getAttribute("employee") != null) {
           Long id=(Long) request.getSession().getAttribute("employee");
            BaseContext.setTl(id);
            chain.doFilter(request, response);
            return;
        }
        if(request.getSession().getAttribute("user") != null){
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setTl(userId);
            chain.doFilter(request,response);
            return;
        }
        String notLogin = JSON.toJSONString(R.error("NOTLOGIN"));
        resp.getWriter().write(notLogin);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
